/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.unal.bioingenium.kbmed.util.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 *
 * @author Alejandro Riveros Cruz
 */
public class Zip {

    public void compressGZip() throws IOException {
        BufferedReader in = new BufferedReader(new FileReader("inputfile.txt"));
        BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("out.gz")));
        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.flush();
        out.close();

        // now decompress our new file
        BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("out.gz"))));
        String s;
        while ((s = in2.readLine()) != null) {
            System.out.println(s);
        }
    }

    public void compressZip() throws IOException {
        FileOutputStream f = new FileOutputStream("out.zip");
        CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32());
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(csum));
        out.setComment("Here is how we compressed in Java");

        // now adding files -- any number with putNextEntry() method
        BufferedReader in = new BufferedReader(new FileReader("1.txt"));
        out.putNextEntry(new ZipEntry("1.txt"));
        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.flush();
        out.close();

        // printing a checksum calculated with CRC32
        System.out.println("Checksum: " + csum.getChecksum().getValue());


        // Now decompress archive
        FileInputStream fi = new FileInputStream("out.zip");
        CheckedInputStream csumi = new CheckedInputStream(fi, new CRC32());
        ZipInputStream in2 = new ZipInputStream(new BufferedInputStream(csumi));
        ZipEntry ze;
        while ((ze = in2.getNextEntry()) != null) {
            System.out.println("Extracting file " + ze);
            int x;
            while ((x = in2.read()) != -1) {
                System.out.write(x);
            }
            System.out.println();
        }
        System.out.println("Checksum extracted: " + csumi.getChecksum().getValue());
        in2.close();
    }
}
